﻿
CREATE proc capquyenmenu_them      
@MaNhomUser int,      
@MaNhomMenu int,      
@MaChuongTrinh int,      
@IDViTri int,      
@ID int      
as      
if exists(select * from QuanTri_CapQuyenNguoiDungSuDungMenu Where ID=@ID)      
begin      
select ErrCode=0      
end      
else      
begin      
if (@MaNhomUser <> 0 and @MaNhomMenu <> 0 and @MaChuongTrinh <> 0 and @IDViTri <> 0)      
begin      
if(exists(select * from QuanTri_CapQuyenNguoiDungSuDungMenu Where  -- MaNhomMenuND=@MaNhomMenu and    
MaNhomUser=@MaNhomUser  and MaChuongTrinh=@MaChuongTrinh and IDViTri=@IDViTri       
))      
begin      
select ErrCode=0      
end      
else      
begin     
  
if exists(select * from QuanTri_PhanNhomMenu Where MaNhomMenuND=@MaNhomMenu)   
begin  
  
insert into QuanTri_CapQuyenNguoiDungSuDungMenu (MaNhomUser,MaNhomMenuND,MaChuongTrinh,IDViTri)      
values(@MaNhomUser,@MaNhomMenu,@MaChuongTrinh,@IDViTri)  
declare @IDCapQuyen as int    
 select @IDCapQuyen=@@IDENTITY
--them tung user  
DECLARE @chuoiuser VARCHAR(8000)  
SELECT @chuoiuser = COALESCE(@chuoiuser+',' ,'') + cast(ID as varchar(50))  
FROM QuanTri_PhanNhomNguoiDung where MaNhomUser=@MaNhomUser  
set @chuoiuser=@chuoiuser+','  
while LEN(@chuoiuser)>0        
begin        
  
declare @IDPhanNhomNguoiDung int  
set @IDPhanNhomNguoiDung =CAST (SUBSTRING(@chuoiuser,0,CHARINDEX(',',@chuoiuser)) as int)  
insert into QuanTri_EditUserRoleInGroup (IDPhanNhomNguoiDung,IDCapQuyen,IDPhanNhomMenu,Quyen_CapNhat,Quyen_Xem,Quyen_Xoa)    
select @IDPhanNhomNguoiDung,@IDCapQuyen,ID as IDPhanNhomMenu,Quyen_CapNhat,Quyen_Xem,Quyen_Xoa   
from QuanTri_PhanNhomMenu Where MaNhomMenuND=@MaNhomMenu      
set @chuoiuser=SUBSTRING(@chuoiuser,CHARINDEX(',',@chuoiuser)+1,LEN(@chuoiuser)-CHARINDEX(',',@chuoiuser))        
end   
-- them tung user  
  
delete from QuanTri_EditUserRoleInGroup Where ISNULL(IDCapQuyen,0)=0  
select ErrCode=1      
end  
else  
begin  
select ErrCode=0      
end  
end      
end      
else      
begin      
select ErrCode=0      
end      
end 